import Taro, {Component} from '@tarojs/taro'
import {
  View,
  Button,
  Text,
  Swiper,
  SwiperItem,
  Image,
  ScrollView,
  OfficialAccount,
  Video,
  Map
} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import {
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtActionSheet,
  AtDrawer,
  AtDivider,
  AtIcon,
  AtAvatar
} from "taro-ui"
import {
  set_userinfo, set_cart, set_goodslist, set_viplist, set_bind_car_num, set_progress,
  set_GyToken, set_pushdatanum, gohome_btn, set_Location, set_wxuser, set_Config
} from '../../actions/IndexAction'

import './index.less'
import set from "../../apis/api"
import "./css/index.css"
import base from "../base"


let page = 0;

var QQMapWX = require('../../components/qqmap/qqmap-wx-jssdk.js');
var qqmapsdk;

class Index extends Component {
  constructor(props) {
    super(props)
    base(this)
    this.state = {
      showgetuserinfo:true,
      value: "",
      show: false,
      jzlist:[],
      jz_detail_list:[]
    }
  }

  config = {
    navigationBarTitleText: '恩杰康节能',
    enablePullDownRefresh: true,
    navigationBarBackgroundColor: "#4bb33d",
    navigationBarTextStyle: "white"

  }

  onShareAppMessage(res) {


    return {
      title: '恩杰康节能',
      path: "/pages/index/index",
      imageUrl: set.server_up + "uploads/15175626017756.jpg",
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          wx.showToast({
            title: '发送成功',
            icon: 'success',
            duration: 2000
          })
        }
      },
      fail: function (res) {

        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          wx.showToast({
            title: '您取消了发送',
            icon: 'none',
            duration: 2000
          })
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
          wx.showToast({
            title: '发送失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
    }
  }

  showDrawer()
  {
    this.setState({
      show:true
    })
  }

  onReachBottom() {
    this.loadmore();
  }

  componentWillReceiveProps(nextProps) {

  }

  getQueryString(url, name) {
    var reg = new RegExp("(^|&?)" + name + "=([^&]*)(&|$)", "i");
    var r = url.match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  }




  loadmore() {
    if (this.state.loadmore) {
      return;
    }
    if (this.state.hasMore) {
      this.setState({
        loadmore: true
      })
    }
    var databody = {
      cart: 0,
      page: page + 1
    }
    var hasmore = false
    this.wx_request(set.v2.goodslist, databody, "POST", {'Content-Type': 'application/x-www-form-urlencoded'}).then((data) => {
      if (data.data.data.list && data.data.data.list.length > 0) {
        page++;
        hasmore = true;
        this.setState({
          list: this.state.list.concat(data.data.data.list),
        })

      }
      this.setState({
        hasMore: hasmore,
        loadmore: false
      })

    }).catch((err) => {
      wx.showToast({
        title: '网络访问失败，请重试',
        icon: 'none',
        duration: 1800
      })
    })

  }

  jump() {
    if (this.state.share_jumped) {
      return;
    }
    var url = decodeURIComponent(this.$router.params.q);
    if (url) {
      var action = this.getQueryString(url, 'action');
      var id = this.getQueryString(url, 'id');
      if (action && id) {
        switch (action) {
          case 'other_pay':
            this.setState({share_jumped: true}, () => {
              Taro.navigateTo({
                url: '/pages/index/other_pay?id=' + id
              })
            })
            break;
        }
      }

    }
    var params = this.$router.params;
    if (params.action) {
      switch (params.action) {
        case 'other_pay':
          var id = params.id
          this.setState({share_jumped: true}, () => {
            Taro.navigateTo({
              url: '/pages/index/other_pay?id=' + id
            })
          })

          break;
        case 'oto_detail':
          var id = params.id
          this.setState({share_jumped: true}, () => {
            Taro.navigateTo({
              url: '/pages/my/otodetail?id=' + id
            })
          })

          break;
        case 'prize':
          this.setState({share_jumped: true}, () => {
            Taro.navigateTo({
              url: '/pages/my/prize_detail'
            })
          })
          break;
        case 'shop':
          this.setState({share_jumped: true}, () => {
            Taro.navigateTo({
              url: '/pages/shop/index'
            })
          })
      }

    }
    if (params.page) {
      this.setState({share_jumped: true}, () => {
        Taro.navigateTo({
          url: params.page
        })
      })
    }
    if (params.switch) {
      this.setState({share_jumped: true}, () => {
        Taro.switchTab({
          url: params.switch
        })
      })
    }


    Taro.switchTab(
      {url: "/pages/index/index"}
    )
    if (this.$router.params.share_url) {
      this.setState({share_jumped: true}, () => {
        Taro.navigateTo({url: "/pages/common/webview?url=" + this.$router.params.share_url})
      })


    } else if (this.$router.params.goods_id) {

      this.setState({share_jumped: true}, () => {
        Taro.navigateTo({url: "/pages/shop/goods?id=" + this.$router.params.goods_id})
      })
    }


  }

  onPullDownRefresh() {
    wx.stopPullDownRefresh()


  }

  componentWillUnmount() {
  }

  getCatch() {
    wx.removeStorageSync("wxuser");
    wx.removeStorageSync("userinfo");

    var wxuser = wx.getStorageSync("wxuser");
    if (wxuser) {
      this.wxuser = JSON.parse(wxuser);
      this.props.dispatch(set_wxuser(this.wxuser))
    }
    var userinfo = wx.getStorageSync("userinfo");
    if (userinfo) {
      this.userinfo = JSON.parse(userinfo)
      this.props.dispatch(set_userinfo(this.userinfo))
    }
  }

  getUserLocation() {
    let vm = this;
    qqmapsdk = new QQMapWX({
      key: vm.props.sys_config.sets.app_key //这里自己的key秘钥进行填充
    });
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  }
  // 获取当前地理位置
  getLocal (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(JSON.stringify(res));
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        vm.props.dispatch(set_Location({
          province: province,
          city: city,
          latitude: latitude,
          longitude: longitude
        }))

      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  }
  // 微信获得经纬度
  getLocation() {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log("定位成功 = ", res)
        var latitude = res.latitude
        var longitude = res.longitude
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        wx.showToast({
          title: '定位失败,请确认您己授权开启定位服务',
          icon: 'none'
        })
      }
    })
  }



  chooseLocation()
  {
    var that=this;
    wx.chooseLocation({
      success: function (res) {
        console.log(res)
        that.setState({
          longitude: res.longitude,
          latitude: res.latitude,
        })
      },
      fail: function (err) {
        console.log(err)
      }
    });
  }
  getConfig(){
    wx.showLoading({title: "加载中..."})
    var databody = {
      access_token: this.props.gytoken.gytoken,
      S_map_key:"gycxc"
    }
    this.wx_request(set.getConfig, databody, "POST", {'Content-Type': 'application/x-www-form-urlencoded'}).then((res) => {
      this.props.dispatch(set_Config(res.data.data))
      this.fetchData();
      wx.hideLoading();
      wx.stopPullDownRefresh()
    }).catch((e)=>{
      console.log(e)
      wx.showToast({title:e.data.msg,icon:"none",duration:1800})
      wx.hideLoading();
      wx.stopPullDownRefresh()
    })
  }
  componentDidShow() {


    this.getUserLocation();

    // console.log(this.$router.params)
    this.checkGyToken().then(()=>{
      this.getwxuser();
      this.getConfig();
      // this.fetchData()
      console.log(this.props.wxuser.wxuser)
    })




   //  this.checkwxuser().then((res) => {
   // //   this.jump();
   //    //是否由分享跳入
   //    if(!this.props.wxuser.wxuser.nickName)
   //    {
   //      Taro.redirectTo({url: "/pages/gypage/login"})
   //      return;
   //    }
   //
   //
   //
   //  });
  }

  fetchData() {
    this.setState({
      jzlist:[]
    })
    wx.showLoading({title: "加载中..."})
    var databody = {
      wxid:this.props.sys_config.sets.wxid,
      access_token: this.props.gytoken.gytoken,
      jd:this.props.location.longitude,
      wd:this.props.location.latitude,
      scope:this.props.sys_config.sets.map_size
    }
    this.wx_request(set.lat_list, databody, "POST", {'Content-Type': 'application/x-www-form-urlencoded'}).then((res) => {
      if(res.data.data)
      {
        var jzlist=[];
        res.data.data.map((item)=>{
          jzlist.push({
            id: item.id,
            latitude: parseFloat(parseFloat(item.wd).toFixed(10)),
            longitude: parseFloat(parseFloat(item.jd).toFixed(10)),
            width:30,
            height:40,
            iconPath:item.status==1?"http://wx.engconn.com/static/uploads/2020-01-13/329751578929760.png":"http://wx.engconn.com/static/uploads/2020-01-13/814321578929816.png",
            callout: {
              content: item.name,
              borderRadius:5,
              padding: 5,
              display: 'ALWAYS',
              textAlign: 'center'
            }
          })
        })

        this.setState({
          jzlist:jzlist,
          jz_detail_list:res.data.data
        })
      }

     wx.hideLoading();
     wx.stopPullDownRefresh()
    }).catch((e)=>{
      console.log(e)
      wx.showToast({title:e.data.msg,icon:"none",duration:1800})
      wx.hideLoading();
      wx.stopPullDownRefresh()
    })
  }

  onPageScroll(e) {
    this.setState({
      title_opac: e.scrollTop / 100 > 1 ? 1 : e.scrollTop / 100
    }, () => {
      console.log(this.state.title_opac)
    })
  }


  clickMarker(val)
  {
    var id=val.markerId;
    this.state.jz_detail_list.map((item)=>{
      if(item.id==id)
      {




        Taro.navigateTo({
          url: '/pages/gypage/jz_detail?item='+JSON.stringify(item)
        })
        return;
      }
    })
  }
  toSearch()
  {
    Taro.navigateTo({url: "/pages/gypage/search"})
  }


  hideDrawer()
  {
    this.setState({
      show:false
    })
  }


  tologin() {
    Taro.navigateTo({
      url: "/pages/my/login"
    })

  }





  render() {
    const {jzlist} = this.state;


    return (

      <View style={{height: "100vh", display: "flex", flexDirection: "column"}}>
        <AtDrawer
          show={this.state.show}
          mask
          onClose={this.hideDrawer.bind(this)}
        >
          <View style={{width:"100%",height:"100%"}}>
            <View style={{display:"flex",alignItems:"center",justifyContent:"center",paddingTop:"50rpx",width:"100%"}}>
              <AtAvatar  size={"large"} circle={true} image={(this.props.wxuser.wxuser&&this.props.wxuser.wxuser.avatarUrl)?this.props.wxuser.wxuser.avatarUrl:""}></AtAvatar>
            </View>
            <View style={{display:"flex",alignItems:"center",justifyContent:"center",paddingTop:"20rpx",width:"100%"}}>
              <Text style={{color: "#999999", fontSize: "26rpx"}}>{(this.props.wxuser.wxuser&&this.props.wxuser.wxuser.nickName)?this.props.wxuser.wxuser.nickName:""}</Text>
            </View>
            <View style={{display:"flex",alignItems:"center",justifyContent:"flex-end",width:"100%",marginTop:"10rpx"}}>
              <View style={{display:"flex",alignItems:"center",paddingTop:"20rpx",width:"96%",marginLeft:"4%",borderBottom:"2rpx solid #eeeeee",paddingBottom:"20rpx"}}>
                <Text style={{color: "#333333", fontSize: "26rpx",marginLeft:"10rpx"}}>账号:</Text>
                <Text style={{color: "#333333", fontSize: "26rpx",marginLeft:"10rpx"}}>{this.props.wxuser.wxuser.tel}</Text>
              </View>
            </View>
            <View style={{display:"flex",alignItems:"center",justifyContent:"flex-end",width:"100%",marginTop:"10rpx"}}>
              <View style={{display:"flex",alignItems:"center",paddingTop:"20rpx",width:"96%",marginLeft:"4%",borderBottom:"2rpx solid #eeeeee",paddingBottom:"20rpx"}}>
                <Text style={{color: "#333333", fontSize: "26rpx",marginLeft:"10rpx"}}>账号:</Text>
                <Text style={{color: "#333333", fontSize: "26rpx",marginLeft:"10rpx"}}>{this.props.wxuser.wxuser.qxz_name}</Text>
              </View>
            </View>
            {/*<View style={{display:"flex",alignItems:"center",justifyContent:"flex-end",width:"100%"}}>*/}
              {/*<View style={{display:"flex",alignItems:"center",paddingTop:"20rpx",width:"96%",marginLeft:"4%",borderBottom:"2rpx solid #eeeeee",paddingBottom:"20rpx"}}>*/}
                {/*<Text style={{color: "#333333", fontSize: "26rpx"}}>角色:{this.props.wxuser.wxuser.qxz_name}</Text>*/}
              {/*</View>*/}
            {/*</View>*/}

          </View>
        </AtDrawer>
        {/*<AtModal isOpened={this.state.wxerror}>*/}
          {/*<AtModalHeader>温馨提示</AtModalHeader>*/}
          {/*<AtModalContent>*/}
            {/*网络不稳定，获取微信信息失败，请点击重试*/}
          {/*</AtModalContent>*/}
          {/*<AtModalAction><Button onClick={this.getwxuser.bind(this)}>重试</Button></AtModalAction>*/}
        {/*</AtModal>*/}
        <View

          style={{
          display: "flex",
          padding: "5rpx",
          alignItems: "center",
          justifyContent:"space-between",
          borderBottom: "5rpx solid #f0f2f5",
          height: "100rpx"
        }}>
          <View onClick={this.showDrawer.bind(this)} style={{display:"flex",marginLeft:"10rpx"}}>
          <AtAvatar  size={"small"} circle={true} image={(this.props.wxuser.wxuser&&this.props.wxuser.wxuser.avatarUrl)?this.props.wxuser.wxuser.avatarUrl:""}></AtAvatar>
          <View style={{display: "flex", padding: "5rpx", alignItems: "center", flex: 1,justifyContent:"center"}}>
            {/*<Text style={{color: "#999999", fontSize: "24rpx"}}>{(this.props.wxuser.wxuser&&this.props.wxuser.wxuser.nickName)?this.props.wxuser.wxuser.nickName:""}</Text>*/}

          </View>
          </View>
          <View style={{flex:1,display:"flex",alignItems:"center",justifyContent:"center"}}>
            <View onClick={this.toSearch.bind(this)} style={{background:"#f0f2f5",borderRadius:"30rpx",height:"60rpx",width:"86%",display:"flex",alignItems:"center",justifyContent:"center"}}>
              <Text style={{fontSize:"26rpx",color:"#999999"}}>
                搜索基站
              </Text>

            </View>
          </View>
          <View style={{display: "flex", padding: "5rpx", alignItems: "center"}}  onClick={this.chooseLocation.bind(this)}>
            <View style={{display: "flex",  alignItems: "center",width:"60rpx",justifyContent:"center"}} >
              {/*<Image src={"../../assets/images/icon_2.png"} style={{width:"30rpx",height:"30rpx",marginRight:"10rpx"}}/>*/}
              <AtIcon prefixClass='icon' value='101' size='26' color='#999999'></AtIcon>
            </View>
            {/*<View style={{display: "flex",  alignItems: "center"}} >*/}
              {/*<Text style={{color: "#999999", fontSize: "24rpx"}}>{this.props.location.city}</Text>*/}
            {/*</View>*/}
            {/*<View style={{display: "flex",  alignItems: "center",marginLeft:"10rpx"}} >*/}
              {/*<Text style={{color: "#999999", fontSize: "24rpx"}}>▼</Text>*/}
            {/*</View>*/}
          </View>
        </View>
        {/*<View style={{background: "#ffffff", height: "100rpx",display:"flex",alignItems:"center",justifyContent:"center"}}>*/}

            {/*<View onClick={this.toSearch.bind(this)} style={{background:"#f0f2f5",borderRadius:"30rpx",height:"60rpx",width:"86%",display:"flex",alignItems:"center",justifyContent:"center"}}>*/}
              {/*<Text style={{fontSize:"26rpx",color:"#999999"}}>*/}
                {/*搜索基站*/}
              {/*</Text>*/}

            {/*</View>*/}
        {/*</View>*/}
        <View style={{flex: 1, background: "#cccccc"}}>

          <Map
            longitude={this.props.location.longitude}
            latitude={this.props.location.latitude}
            markers={jzlist}
            scale={this.props.sys_config.sets.map_zoom}
            onMarkerTap={this.clickMarker.bind(this)}
            style={{width: "100%", height: "100%"}}/>
        </View>



      </View>
    )
  }
}


const mapstate = state => {
  return {
    userinfo: state.usermodel,
    cart_num: state.cart_num,
    cart: state.cart,
    goodslist: state.goodslist,
    vip: state.vip,
    progress: state.progress,
    pushdata: state.pushdata,
    wxuser: state.wxusermodel,
    gytoken:state.gytoken,
    location:state.location,
    sys_config:state.sys_config
  }
}
export default connect(mapstate)(Index)

